package com.nvn.androidapp.adapters;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nvn.androidapp.R;
import com.nvn.androidapp.Objects.Document;
import com.nvn.androidapp.utils.Statics;



public class ImageAdapter extends BaseAdapter{

	private Activity mContext;
	private List<Document> pics;
	private LayoutInflater inflater;
	
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
	
	public ImageAdapter(Activity _context,List<Document> objects) {
		super();
		
		this.mContext = _context;
		this.pics=objects;
		this.inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.ic_no_image)
			.showImageForEmptyUri(R.drawable.ic_no_image)
			.showImageOnFail(R.drawable.ic_no_image)
			.cacheInMemory()
			.cacheOnDisc()
			.bitmapConfig(Bitmap.Config.RGB_565)
			.build();
	}
	
	@Override
	public View getView(final int position, View v, ViewGroup parent) {
		final Document doc = getItem(position);
		
		if (v == null) {
			v = (ImageView) inflater.inflate(R.layout.item_grid_image, null);
		}
		final ImageView imv = (ImageView)v;
		
		Bitmap bitmap = BitmapFactory.decodeByteArray(doc.getThumb() , 0, doc.getThumb().length);
		imv.setImageBitmap(bitmap);
		
		imv.setLayoutParams(new LayoutParams(Statics.PixelFromDp(mContext, Statics.SQUARE_MATRICS), Statics.PixelFromDp(mContext, Statics.SQUARE_MATRICS)));
		
//		v.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View arg0) {
//				MainActivity m = (MainActivity) mContext;
//				m.setNewPage(ViewPagerFragment.newInstance(doc.getID(), ""));
//			}
//		});
	    return v;
	}

	
	public class ViewHolder{
		ImageView imv;
	}

	@Override
	public int getCount() {
		return pics.size();
	}

	@Override
	public Document getItem(int position) {
		return pics.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}
	public void setData(List<Document> ob){
		this.pics=ob;
		this.notifyDataSetChanged();
	}

}
